// api.ts
import { getToken } from '../login/loginApi';
const apiHost = import.meta.env.VITE_API_HOST || '';
const BASE_URL = apiHost+'/documents/audit';

interface AuditData {
    statutes: Array<{
        clause_number: string;
        section: string;
        content: string;
    }>;
    key_points: string[];
    department: string[];
    description: string;
}

export const fetchAudits = async (pageIndex: number, pageSize: number, clauseNumber?: string, department?: string, section?: string) => {
    const params = new URLSearchParams();

   
    if (pageIndex) params.append('page_index', pageIndex.toString());
    if (pageSize) params.append('page_size', pageSize.toString());
    if (clauseNumber) params.append('clause_number', clauseNumber);
    if (department) params.append('department', department);
    if (section) params.append('section', section);

    const response = await fetch(`${BASE_URL}/list?${params.toString()}`, {
        method: 'GET',
        headers: {
            "Authorization": `Bearer ${getToken()}`,
        },
    });

    return response.json();
};

export const fetchAuditById = async (id: string) => {
    const response = await fetch(`${BASE_URL}/${id}`, {
        method: 'GET',
        headers: {
            "Authorization": `Bearer ${getToken()}`,
        },
    });

    return response.json();
};

export const createAudit = async (data: AuditData) => {
    const response = await fetch(BASE_URL, {
        method: 'POST',
        headers: {
            "Authorization": `Bearer ${getToken()}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    });

    return response.json();
};

export const updateAudit = async (data: AuditData & { audit_rule_id: string }) => {
    const response = await fetch(BASE_URL, {
        method: 'PUT',
        headers: {
            "Authorization": `Bearer ${getToken()}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    });

    return response.json();
};

export const deleteAudit = async (id: string) => {
    const response = await fetch(`${BASE_URL}/${id}`, {
        method: 'DELETE',
        headers: {
            "Authorization": `Bearer ${getToken()}`,
        },
    });

    return response.json();
};